package pemks.servlet;/**
 * @description:  
 * @author kl
 * @date 2025/4/4 下午9:38
 * @version 1.0
 */
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pemks.entity.File;
import pemks.util.DBUtil;


import java.io.*;
import java.sql.*;

import com.google.gson.*;
import pemks.dao.FileDAO;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(
        name = "FileServlet",
        urlPatterns = {"/file/post_CT", "/file/Tw_search",
                "/file/download_id", "/file/del_file"},
        loadOnStartup = 1
)
public class FileServlet extends HttpServlet {
    private FileDAO fileDAO = new FileDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        JsonObject jsonResponse = new JsonObject();

        try {
            switch (path) {
                case "/post_CT":
                    handleUploadCT(request, jsonResponse);
                    break;
                case "/Tw_search":
                    handleKeywordSearch(request, jsonResponse);
                    break;
                case "/del_file":
                    handleDeleteFile(request, jsonResponse);
                    break;
                case "/download_id":
                    handleDownload(request, response);
                    break;
                default:
                    sendError(response, 404, "Invalid endpoint");
            }
        } catch (Exception e) {
            sendError(response, 500, "Server error: " + e.getMessage());
        }

        response.getWriter().print(jsonResponse.toString());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        if (request.getServletPath().equals("/smartgrid/download_id")) {
            handleDownload(request, response);
        }
    }

    // 处理文件上传（加密后密文）
    private void handleUploadCT(HttpServletRequest request, JsonObject json) {
        String cipherText = request.getParameter("upload_CT");
        String owner = request.getParameter("upload_DO");
        String Tw = request.getParameter("Tw");

        if (cipherText == null || owner == null || Tw == null) {
            json.addProperty("status", 400);
            json.addProperty("message", "Missing required parameters");
            return;
        }

        int fileId = fileDAO.saveFile(owner, cipherText, Tw);
        if (fileId != -1) {
            json.addProperty("status", 200);
            json.addProperty("data", fileId);
        } else {
            json.addProperty("status", 500);
            json.addProperty("message", "Failed to save file");
        }
    }

    // 处理关键词搜索
    private void handleKeywordSearch(HttpServletRequest request, JsonObject json) {
        String Tw = request.getParameter("Tw");
        List<pemks.entity.File> files = fileDAO.searchByKeywords(Tw);

        JsonArray results = new JsonArray();
        files.forEach(file -> {
            JsonObject obj = new JsonObject();
            obj.addProperty("id", file.getId());
            obj.addProperty("owner", file.getOwner());
            results.add(obj);
        });

        json.add("data", results);
        json.addProperty("status", 200);
    }

    // 处理文件下载
    private void handleDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileId = request.getParameter("download_id");
        File file = fileDAO.getFileById(Integer.parseInt(fileId));

        if (file != null) {
            response.setContentType("text/plain");
            response.getWriter().print(file.getCipherText());
        } else {
            sendError(response, 404, "File not found");
        }
    }

    // 处理文件删除
    private void handleDeleteFile(HttpServletRequest request, JsonObject json) {
        int fileId = Integer.parseInt(request.getParameter("delID"));
        String owner = request.getParameter("del_DO");

        if (fileDAO.deleteFile(fileId, owner)) {
            json.addProperty("status", 200);
            json.addProperty("message", "success");
        } else {
            json.addProperty("status", 403);
            json.addProperty("message", "Permission denied or file not exist");
        }
    }

    private void sendError(HttpServletResponse response, int code, String msg)
            throws IOException {
        response.setStatus(code);
        JsonObject error = new JsonObject();
        error.addProperty("status", code);
        error.addProperty("message", msg);
        response.getWriter().print(error.toString());
    }
}
